package G.二叉搜索树;

public class _701_二叉搜索树中的插入操作 {
    /**
     * 自解：递归法
     * @param root
     * @param val
     * @return
     */
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null){
            root = new TreeNode(val);
            return root;
        }

        if (root.val < val){
            if (root.right == null){
                root.right = new TreeNode(val);
                return root;
            }else {
                insertIntoBST(root.right,val);
            }

        }else {
            if (root.left == null){
                root.left = new TreeNode(val);
                return root;
            }else {
                insertIntoBST(root.left,val);
            }
        }

        return root;

    }

    /**
     * 自解：迭代==没办法做 因为无法保留root的前一个 所以最后新增的无法跟上面的树连起来
     */
    public TreeNode insertIntoBST1(TreeNode root, int val) {

        if (root==null){
            return new TreeNode(val);
        }
        TreeNode node = new TreeNode(-1);
        node.right = root;
        TreeNode prev = root;

        while (root != null){

            root = root.val<val?root.right:root.left;

        }

        root = new TreeNode(val);
        return node.right;
    }
}
